<template>
  <div class="home">
    <!-- Banner横幅区域 -->
    <div class="home-banner">
      <div class="homediv" v-if="SubjectI == 13">
        <div class="homename">高考倒计时</div>
        <div class="hometime">
          <div class="hometimelist">
            <span class="countdown-item">{{ days }}</span>
            <div class="countdown-label">DAYS</div>
          </div>
          <div class="hometimelist">
            <span class="countdown-item">{{ hours }}</span>
            <div class="countdown-label">HOURS</div>
          </div>
          <div class="hometimelist">
            <span class="countdown-item">{{ minutes }}</span>
            <div class="countdown-label">MINUTES</div>
          </div>
          <div class="hometimelist">
            <span class="countdown-item">{{ seconds }}</span>
            <div class="countdown-label">SECONDS</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="home-main">
      <!-- 左侧列 -->
      <div class="home-left">

        <!-- 今日课题计划 -->
        <div class="course-plan-card">
          <h4 style="margin: 0 0 10px 0; font-weight: 700">今日课程计划</h4>
          <a-table :pagination="false" :data="formdata.todayCrs" :bordered="false" :scroll="{ x: 150 }">
            <template #columns>
              <a-table-column title="课程" align="center" data-index="VideoName" :width="150">
                <template #cell="{ record }">
                  <a-tooltip :content="record.VideoName">
                    <div class="testVideoName" style="padding: 0.1vw" v-on:click="nameClick(record)">
                      {{ record.VideoName }}
                    </div>
                  </a-tooltip>
                </template>
              </a-table-column>
            </template>
          </a-table>
        </div>
        <!-- 今日学习计划 -->
        <div class="study-plan-card">
          <h4 style="margin: 0 0 10px 0; font-weight: 700">今日练习计划</h4>
          <a-table :pagination="false" :data="formdata.todayPrac.slice(0, 4)" :bordered="false">
            <template #columns>
              <a-table-column title="知识点名称" align="center" data-index="KlName" :width="150">
                <template #cell="{ record }">
                  <a-tooltip :content="record.KlName">
                    <div class="testVideoName" style="padding: 0.1vw">
                      {{ record.KlName }}
                    </div>
                  </a-tooltip>
                </template>
              </a-table-column>
              <a-table-column align="center" data-index="name" :width="150">
                <template #cell="{ record }">
                  <span class="practice" @click="problemsolving(record)">开始练习</span>
                </template>
              </a-table-column>
            </template>
          </a-table>
        </div>
      </div>

      <!-- 右侧列 -->
      <div class="home-right">
        <!-- 本周学习时长 -->
        <div class="study-duration-card">
          <div class="duration-chart">
            <TimeEcharts v-if="bar_listdata" :bar_list="bar_list" :key="`time-${bar_listdataKey}`"
              :bar_listdata="bar_listdata" />
            <a-empty v-if="!bar_listdata" class="empty" />
          </div>
          <div class="duration-data">
            <div class="data-item">
              <p>本周学习时长 (h)</p>
              <p class="duration-time">{{ formdata.Time.weekTime }}</p>
            </div>
            <div class="data-item">
              <p>较上周时长 (h)</p>
              <p class="duration-time">{{ formdata.Time.vsTime }}</p>
            </div>
          </div>
        </div>

        <!-- 底部两个卡片 -->
        <div class="bottom-cards">
          <!-- 课程完成情况 -->
          <div class="completion-card">
            <h4 style="margin: 0 0 10px 0; font-weight: 700">课程完成情况</h4>
            <PieChart v-if="Cfinish" :Cfinish="Cfinish" :key="`pie-${CfinishKey}`" />
            <a-empty v-if="!Cfinish" class="empty" />
          </div>

          <!-- 学习轨迹 -->
          <div class="learning-track-card">
            <h4 style="margin: 0 0 10px 0; font-weight: 700">学习轨迹</h4>
            <Broken v-if="week_listdata" :week_listdata="week_listdata" :key="`broken-${week_listdataKey}`"
              :week_listrawData="week_listrawData" />
            <a-empty v-if="!week_listdata" class="empty" />
          </div>
        </div>
      </div>
    </div>
  </div>
  <a-modal v-model:visible="visible" @ok="handleOk" width="50vw" @cancel="handleCancel">
    <template #title> {{ videoname }} </template>
    <div>
      <video ref="videoEl" controls :poster="poster" width="100%" class="videos-height"></video>
    </div>
  </a-modal>
  <a-modal v-model:visible="hasSubject" @ok="handleCheckSubject" @cancel="handleSubjectCancel" okText="确认开通"
    cancelText="去测评" :closable="false" :mask-closable="false">
    <template #title>
      提示
    </template>
    <div>
      <p style="line-height: 30px;">选择开通课程</p>
      <a-radio-group v-model="courseType">
        <a-radio value="1">基础课程</a-radio>
        <a-radio value="2">进阶课程</a-radio>
        <a-radio value="3">拔高课程</a-radio>
      </a-radio-group>
    </div>
  </a-modal>
</template>
<script lang="ts" setup>
import { ref, reactive, onMounted, onUnmounted, watch, onBeforeUnmount } from "vue";
// import { useUserStore } from '@/store';
import { Message } from "@arco-design/web-vue";
import Barecharts from "./echarts/barecharts.vue";
import Broken from "./echarts/broken.vue";
import TimeEcharts from "./echarts/timeEcharts.vue";
import PieChart from "./echarts/piechart.vue";
import { HomeStatisticsindex, getCourseList,createCourse } from "@/api/home";
import { catstudyCourse } from "@/api/study";
import useUserStore from "@/store/modules/user";
import { useRouter } from "vue-router";
import Hls from "hls.js";
import { customSetItem } from "@/utils/LocalStorageService";
const userStore = useUserStore();
// import useUserStore from '@/store/modules/user/index';
const router = useRouter();
let subjectID = userStore.$state.subjectID;
// const storedPermission = JSON.parse(localStorage.getItem("permission"));
// if(storedPermission){
//   if (storedPermission.subjectIds.length > 0) {
//     subjectID = storedPermission.subjectIds[0];
//   }
// }
// console.log('这是subjectID',subjectID);

const windowWidth = ref(window.innerWidth);
const courseType = ref("1");
// 创建响应式对象
let myObject = reactive({});
const data = reactive([
  {
    key: "1",
    name: "Jane Doe",
    salary: 23000,
    className: "32 ",
    email: "jane.doe@example.com",
    expand: "Expand Data",
  },
  {
    key: "2",
    name: "Alisa Ross",
    className: 25000,
    address: "35 Park Road, London",
    email: "alisa.ross@example.com",
  },
  {
    key: "3",
    name: "Kevin Sandra",
    className: 22000,
    address: "31 Park Road, London",
    email: "kevin.sandra@example.com",
  },
  {
    key: "4",
    name: "Ed Hellen",
    className: 17000,
    address: "42 Park Road, London",
    email: "ed.hellen@example.com",
  },
  {
    key: "5",
    name: "William Smith",
    className: 27000,
    address: "62 Park Road, London",
    email: "william.smith@example.com",
  },
  {
    key: "5",
    name: "William Smith",
    className: 27000,
    address: "62 Park Road, London",
    email: "william.smith@example.com",
  },
]);

const isHasCounse = ref(false);
const getCourseListData = () => {
  getCourseList({
    sid: subjectID,
    page: 1,
    limit: 12
  }).then((res) => {
    if (JSON.stringify(res) == '{}') {
      hasSubject.value = true;
    }
  });
};

const handleCheckSubject = () => {
  hasSubject.value = false;
  let data = {
    type:courseType.value,
    subjectID: subjectID
  }
  createCourse(data).then((res) => {
    router.push({
    path: "/Study",
    query:{
      mine:1
    }
  })
  });
}
const handleSubjectCancel = () => {
  hasSubject.value = false;
  router.push({
    path: "/Measure"
  })
}

const checkHasSubject = (sid) => {
  let subject = localStorage.getItem("subject");
  var arr = JSON.parse(subject).map(String);
  // 判断是否有开通课程
  if (arr.indexOf(sid) == -1) {
    Message.warning("您还未开通当前学科！");
  } else {
    getCourseListData();
  }
};

const targetDate = new Date("2026-06-07T09:00:00").getTime();
const days = ref<number>(0);
const hours = ref<number>(0);
const minutes = ref<number>(0);
const seconds = ref<number>(0);
let countdownInterval: ReturnType<typeof setInterval>;
const updateCountdown = () => {
  const now = new Date().getTime();
  const distance = targetDate - now;
  if (distance < 0) {
    clearInterval(countdownInterval);
    days.value = 0;
    hours.value = 0;
    minutes.value = 0;
    seconds.value = 0;
    return;
  }
  days.value = Math.floor(distance / (1000 * 60 * 60 * 24));
  hours.value = Math.floor(
    (distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)
  );
  minutes.value = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
  seconds.value = Math.floor((distance % (1000 * 60)) / 1000);
};
const RefundReadForm = reactive({
  subjectId: subjectID,
});

const bar_chartdata = ref();
const rawData = ref();
//折线图
const week_listdata = ref();
const week_listrawData = ref();

// 右侧柱状图
const bar_list = ref();
const bar_listdata = ref();

//饼图
const Cfinish = ref();
const formdata = reactive({
  bar_chart: [], //柱状图
  bar_list: [], //折线图
  week_list: {},
  Time: {},
  todayPrac: [], //今日练习计划
  todayCrs: [], //今日课程计划
  Cfinish: {}, //课程完成情况
});

// 添加这些 key 变量
const bar_chartdataKey = ref(0);
const week_listdataKey = ref(0);
const bar_listdataKey = ref(0);
const CfinishKey = ref(0);

const statistics = () => {

  if (week_listdata.value) {
    week_listdata.value = [];
    week_listrawData.value = [];
  }
  // 在更新数据前增加 key 值，强制子组件重新渲染
  bar_chartdataKey.value++;
  week_listdataKey.value++;
  bar_listdataKey.value++;
  CfinishKey.value++;

  HomeStatisticsindex(RefundReadForm).then((res: any) => {
    bar_chartdata.value = res.bar_chart.data;
    rawData.value = res.bar_chart.rawData;
    bar_list.value = res.week_list.data;
    bar_listdata.value = res.week_list.rawData;
    // formdata.bar_list = res.bar_list;
    week_listdata.value = processDateArray(res.bar_list.data);

    week_listrawData.value = res.bar_list.rawData;
    Cfinish.value = res.Cfinish;
    formdata.Time = res.Time;
    formdata.todayPrac = res.todayPrac;
    formdata.todayCrs = res.todayCrs;
    // formdata.Cfinish = res.Cfinish;

  });
};
const visible = ref(false);
const hasSubject = ref(false);
const videoEl = ref<HTMLVideoElement | null>(null);
const hlsInstance = ref<Hls | null>(null);
const poster = ref(""); // 视频封面URL
const videoUrl = ref(""); // M3U8视频URL
const VideoTime = ref();
// 点击课题名称
const nameClick = (e: any) => {
  visible.value = true;
  from.vid = e.VID;
  poster.value = e.CoverPath;
  videoUrl.value = e.ListPath;
  videoname.value = e.VideoName;
  video();
};

const from = reactive({
  page: "1",
  limit: "10",
  vid: "",
});
const videoList = ref();
const videoname = ref();
const video = () => {
  // if (route.query.id == "1") {
  //   from.vid = receivedData;
  // }

  catstudyCourse(from).then((res: any) => {
    videoList.value = res.videoList;
    VideoTime.value = videoList.value.VideoTime - 1;

    if (videoUrl.value) {
      initHlsPlayer().then(() => {
        // startTracking(); // 初始化后开始跟踪
      });
    }
  });
};

const handleOk = () => {
  visible.value = false;
  destroyHlsPlayer();

};
const handleCancel = () => {
  visible.value = false;
  destroyHlsPlayer();
};
// 销毁HLS实例
const destroyHlsPlayer = () => {
  if (hlsInstance.value) {
    hlsInstance.value.destroy();
    hlsInstance.value = null;
  }

  // 1. 清除定时器
  // if (intervalId.value) {
  //   clearInterval(intervalId.value);
  //   intervalId.value = null;
  // }
  // 2. 移除video元素的事件监听
  if (videoEl.value) {
    // videoEl.value.removeEventListener("timeupdate", handleTimeUpdate);
    // 重置video元素
    videoEl.value.pause();
    videoEl.value.removeAttribute("src");
    videoEl.value.load();
  }
};

// 初始化HLS播放器
const initHlsPlayer = async () => {
  if (!videoEl.value) return;
  // videoEl.value.addEventListener("timeupdate", handleTimeUpdate);
  try {
    if (Hls.isSupported()) {
      hlsInstance.value = new Hls();
      hlsInstance.value.loadSource(videoUrl.value);
      hlsInstance.value.attachMedia(videoEl.value);
      hlsInstance.value.on(Hls.Events.MANIFEST_PARSED, () => {
        videoEl.value?.play().catch((e) => {
          console.error("自动播放失败:", e);
        });
      });

      hlsInstance.value.on(Hls.Events.ERROR, (event, data) => {
        if (data.fatal) {
          switch (data.type) {
            case Hls.ErrorTypes.NETWORK_ERROR:
              console.error("网络错误，尝试恢复...");
              hlsInstance.value?.startLoad();
              break;
            case Hls.ErrorTypes.MEDIA_ERROR:
              console.error("媒体错误，尝试恢复...");
              hlsInstance.value?.recoverMediaError();
              break;
            default:
              console.error("无法恢复的错误");
              // destroyHlsPlayer();
              break;
          }
        }
      });
    } else if (videoEl.value.canPlayType("application/vnd.apple.mpegurl")) {
      // 原生支持HLS的浏览器（如Safari）
      videoEl.value.src = videoUrl.value;
      videoEl.value.addEventListener("loadedmetadata", () => {
        videoEl.value?.play().catch((e) => {
          console.error("自动播放失败:", e);
        });
      });
    }
  } catch (error) {
    console.error("初始化HLS播放器失败:", error);
  }
};
// 处理日期数组，提取月日部分
function processDateArray(dateArray) {
  return dateArray.map(dateStr => {
    // 假设日期格式为 "YYYY-MM-DD"
    const parts = dateStr.split('-');
    if (parts.length >= 3) {
      // 返回 "MM-DD" 格式
      return `${parts[1]}-${parts[2]}`;
    }
    // 如果格式不匹配，返回原始值
    return dateStr;
  });
}

// 使用示例
// week_listdata.value = 
const problemsolving = (record: any,) => {
  localStorage.setItem("index", String('2'));
  customSetItem("index", String('2'));
  // if (index == 1) {
  router.push({
    path: "/Measure/answerQuestions",
    query: {
      klID: record.KlID,
      saveName: record.KlName,
      subjectID: RefundReadForm.subjectId,
      type: 5,
    },
  });
};
watch(
  () => userStore.$state.subjectID,
  async (newValue, oldValue) => {

    try {
      RefundReadForm.subjectId = newValue;
      if (userStore.$state.subjectID) {
        await statistics();
        checkHasSubject(userStore.$state.subjectID)
      }

      // docsaveData.value = data;
    } catch (error) {
      console.error("获取数据出错:", error);
    }
  },
  { immediate: true }
);
const SubjectI = ref()
onMounted(() => {
  updateCountdown();
  SubjectI.value = localStorage.getItem("SubjectID");
  if (RefundReadForm.subjectId) {
    // statistics();
  }
  countdownInterval = setInterval(updateCountdown, 1000);
});
onBeforeUnmount(() => {
  destroyHlsPlayer();
  // 最终保存一次进度
  // if (maxPlayedDuration.value > 0) {
  //   savePlayProgress(maxPlayedDuration.value);
  // }
  // if (videosRightRef.value) {
  //   videosRightRef.value.removeEventListener("scroll", handleScroll);
  // }
});
onUnmounted(() => {
  // 从 localStorage 获取值并添加到对象
  // myObject = JSON.parse(localStorage.getItem('permission') as any);


  clearInterval(countdownInterval);
});
</script>
<style lang="less" scoped>
/* 禁止表格滚动 */
:deep .ant-table {
  overflow: hidden;
  // overflow-x: hidden !important;
  // overflow-y: hidden !important;
}

.empty {
  margin-top: 0vw;
}

.home {
  width: 100%;
  height: 100%;
  background: #f7fbff;
  padding: 24px;
}

/* Banner横幅区域 */
.home-banner {
  width: 100%;
  height: 200px;
  background-color: #fff;
  background-image: url("/img/shanyaozhe.png");
  background-size: 100% 100%;
  border-radius: 24px;
  margin-bottom: 24px;
  display: flex;
  justify-content: flex-end;
  position: relative;
}

/* 主要内容区域 */
.home-main {
  display: flex;
  gap: 24px;
}

/* 左侧列 */
.home-left {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.study-plan-card {
  flex: 1;
  padding: 24px;
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}

.course-plan-card {
  flex: 1;
  padding: 24px;
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}

/* 右侧列 */
.home-right {
  flex: 1.5;
  display: flex;
  flex-direction: column;
  gap: 24px;
}

/* 本周学习时长卡片 */
.study-duration-card {
  flex: 1;
  padding: 24px;
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
  display: flex;
  flex-direction: row;
}

.duration-chart {
  flex: 1;
  margin-bottom: 16px;
}

.duration-data {
  display: flex;
  align-items: center;
  background: #f7fbff;
  border-radius: 8px;
  padding: 16px;
  flex-direction: column;
  width: 200px;
}

.data-item {
  flex: 1;
  text-align: center;
}

.data-item p:first-child {
  font-weight: 400;
  font-size: 16px;
  color: #8393a3;
  line-height: 22px;
  margin: 0 0 8px 0;
}

.duration-time {
  font-weight: 500;
  font-size: 36px;
  color: #03305c;
  line-height: 50px;
  margin: 0;
}

.data-divider {
  width: 1px;
  height: 64px;
  background: #ededed;
  margin: 0 16px;
}

/* 底部两个卡片 */
.bottom-cards {
  display: flex;
  gap: 24px;
  height: 300px;
}

.completion-card {
  flex: 1;
  padding: 24px;
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}

.learning-track-card {
  flex: 1;
  padding: 24px;
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .home {
    padding: 12px;
  }

  .home-banner {
    height: 150px;
    margin-bottom: 16px;
  }

  .home-main {
    flex-direction: column;
    height: auto;
    gap: 16px;
  }

  .home-left {
    gap: 16px;
  }

  .home-right {
    gap: 16px;
  }

  .bottom-cards {
    flex-direction: column;
    height: auto;
    gap: 16px;
  }

  .study-duration-card,
  .completion-card,
  .learning-track-card,
  .study-plan-card,
  .course-plan-card {
    padding: 16px;
  }

  .duration-time {
    font-size: 24px;
  }
}

.practice {
  color: #0075ff;
  cursor: pointer;
  text-decoration: underline;
}

.homediv {
  width: 500px;
  margin-right: 30px;
  justify-content: flex-end;
}

.homename {
  height: 26px;
  text-align: center;
  line-height: 26px;
  font-family: PingFangSC, PingFang SC;
  font-weight: 500;
  font-size: 15px;
  color: #0075ff;
  box-shadow: 0 0 2px 1px #5695f7;
  padding: 0 5px;
  background: linear-gradient(to right, #5695f7, #aed2f8);
  opacity: 0.8;
  float: right;
  color: #fff;
  margin: 50px 17px 10px 0;
}

.hometime {
  width: 100%;
  display: flex;
  justify-content: flex-end;
}

.hometimelist {
  width: 4vw;
  height: 4vw;
  padding: 0px 0.5rem;
  text-align: center;
  margin: 0 0.937rem 0 0;
  background-image: url("/img/daojishi1.png");
  background-size: 100% 100%;
}

.countdown-item {
  font-family: DINAlternate, DINAlternate;
  font-weight: bold;
  font-size: 2vw;
  color: #ffffff;
  margin: 0.5vh 0 0 0;
  display: inline-block;
  text-align: center;
  font-style: normal;
}

.countdown-label {
  font-family: PingFangSC, PingFang SC;
  font-weight: 500;
  font-size: 0.6vw;
  color: #ffffff;
}

.testVideoName {
  white-space: nowrap;
  /* 禁止换行 */
  overflow: hidden;
  /* 隐藏超出内容 */
  text-overflow: ellipsis;
  /* 显示省略号 */
  cursor: pointer;
  /* 鼠标悬停时显示手型 */
  width: 100%;
  overflow: hidden;
  // width: 80%;
}

/* 移动端特殊样式 */
@media (max-width: 768px) {
  .homediv {
    width: 35%;
    margin-right: 30px;
  }

  .homename {
    height: 3vh;
    text-align: center;
    line-height: 26px;
    font-family: PingFangSC, PingFang SC;
    font-weight: 500;
    font-size: 12px;
    color: #0075ff;
    box-shadow: 0 0 2px 1px #5695f7;
    padding: 0 5px;
    background: linear-gradient(to right, #5695f7, #aed2f8);
    opacity: 0.8;
    float: right;
    color: #fff;
    margin: 10px 0px 10px 0;
  }

  .hometimelist {
    width: 8vw;
    height: 8vw;
    padding: 0px 0.5rem;
    text-align: center;
    margin: 0 1vw 0 0;
    background-image: url("/img/daojishi1.png");
    background-size: 100% 100%;
  }

  .countdown-label {
    font-family: PingFangSC, PingFang SC;
    font-size: 10px;
    color: #ffffff;
  }

  .countdown-item {
    font-size: 16px;
  }
}
</style>
